import {COUPON_ENUM} from "./constant/index";
import {toast} from "./utils/tool";
import EventBus from "./utils/eventBus";

function getCatch() {
    const user = wx.getStorageSync('user')
    return user || null
}

App({
    clearOrderCache() {
        wx.removeStorage({
            key: "order_cache"
        })
    },
    getUserInfo() {
        return new Promise((resolve, reject) => {
            wx.login({
                success: loginRes => {
                    this.ajax({
                        url: '/api/index/login',
                        data: {
                            code: loginRes.code
                        },
                        success: res => {
                            if (res.code === 1) {
                                const {data} = res
                                this.globalData.hasLogin = true
                                wx.setStorageSync('user', data)
                                const {token} = data
                                wx.setStorageSync('token', token);
                                this.globalData.userInfo = data
                                this.globalData.userData = data
                                this.globalData.token = token
                                resolve(res)
                                return
                            }
                            reject(res)
                        },
                        fail: err => {
                            reject(err)
                        }
                    });
                }
            });
        })
    },
    onLaunch: function () {
        this.devTool()
        this.appUpdate()
        // this.updateApp()
        // wx.getLocation({
        //     type: 'gcj02',
        //     success: res => {
        //         console.log('emit location')
        //         EventBus.$emit('getLocationSuccess', res)
        //     }
        // })
        // if (this.globalData.loading) return
        // this.globalData.loading = true
        // this.getUserInfo().catch(null)
    },
    globalData: {
        token: wx.getStorageSync('token') || '',
        loading: false,
        hasLogin: false,
        showFlag: false,
        userInfo: getCatch(),
        firstStore: wx.getStorageSync('firststore') || '',
        payOption: [],
        couponData: {
            [COUPON_ENUM.COUPON]: [],
            [COUPON_ENUM.GROUP]: []
        },
        userData: {},
        roomList: [],
        firstData: {},
        shopList: [],
        location: wx.getStorageSync('location') || {
            lat: '',
            lon: ''
        },
        indexType: 0,
        selectStore: null
    },
    appUpdate() {
        const updateManager = wx.getUpdateManager()
        updateManager.onUpdateReady(() => {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success: ev => {
                    if (ev.cancel) return
                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                    updateManager.applyUpdate()
                }
            })
        })
    },
    setLocation(data) {
        wx.setStorageSync('location', data)
        this.globalData.location = data
    },
    updateUserInfo() {
        return new Promise((resolve, reject) => {
            this.ajax({
                url: '/api/user/userinfo',
                success: res => {
                    if (res.code === 1) {
                        const {data} = res
                        this.setUserData(data)
                        return resolve(data)
                    }
                    reject(res)
                }
            })
        })
    },
    checkHasMobile() {
        const {userInfo} = this.globalData
        if (!userInfo) return toast({title: '请先绑定手机号', time: 1500}, () => {
            wx.navigateTo({url: "/pages/login/login"})
        })
        const {mobile} = userInfo
        if (!!mobile) return true
        return toast({title: '请先绑定手机号', time: 1500}, () => {
            wx.navigateTo({url: "/pages/login/login"})
        })
    },
    devTool() {
        const value = wx.getStorageSync('firststore')
        if (!!value && typeof value === 'object' && Array.isArray(value)) {
            wx.removeStorageSync('firststore')
            this.globalData.firstStore = null
        }
    },
    getShopList() {
        return this.globalData.shopList
    },
    setShopList(data = []) {
        const result = []
        data.forEach((item, index) => {
            item = item.map(good => ({...good, index}))
            result.push(...item)
        })
        this.globalData.shopList = result
    },
    getFirst() {
        return this.globalData.firstStore
    },
    setFirst(data) {
        this.globalData.firstStore = {...data}
        wx.setStorageSync('firststore', data)
    },
    getRoomList() {
        return this.globalData.roomList
    },
    setRoomList(data) {
        console.log(data, 'setRoomList')
        if (!data || !data.length) return this.globalData.roomList.splice(0, this.globalData.roomList.length)
        this.globalData.roomList.splice(0, this.globalData.roomList.length, ...data)
    },
    setUserData(data) {
        this.globalData.userData = {...data}
        this.globalData.userInfo = {...data}
    },
    getUserData() {
        return this.globalData.userData
    },

    async initCouponData() {
        const coupon = await this.getCouponData(COUPON_ENUM.COUPON)
        // const group = await this.getCouponData(COUPON_ENUM.GROUP)
        return {
            couponLen: coupon.length, groupLen: 0,
            coupon
        }
    },

    formatDate(time) {
        const date = new Date(time * 1000)
        const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
        return `${year}-${month < 10 ? '0' + month : month}-${day >= 10 ? day : '0' + day}`
    },

    getCouponData(type) {
        return new Promise(resolve => {
            const url = {
                [COUPON_ENUM.COUPON]: '/api/user/coupons',
                [COUPON_ENUM.GROUP]: "/api/coupon/couponlist",
            }
            this.ajax({
                url: url[type],
                success: resp => {
                    const {code, data, msg} = resp
                    if (code !== 1) {
                        toast({title: msg})
                        return resolve([])
                    }
                    if (data && data.length) {
                        this.globalData.couponData[type] = [...data]
                        resolve(data)
                    }
                }
            })
        })
    },
    api_url: 'https://sanju.xinyunweb.com',
    // 开锁域名
    unlocking: 'http://ops.huohetech.com',
    ajax: function (o, show) {
        if (show) {
            wx.showLoading({
                mask: true,
                title: '正在加载...'
            });
        }
        const data = o.data || {};
        data.token = this.globalData.token
        wx.request({
            url: this.api_url + o.url,
            data: data,
            method: o.method || 'POST',
            header: o.header || {
                // 请求头
                'content-type': 'application/json',
            },
            success: function (res) {
                if (show) {
                    wx.hideLoading();
                }
                if (res && res.data && res.data.code !== undefined) {
                    if (res.data.code == -1) {
                        wx.showToast({
                            title: '未登录或登陆已失效',
                            icon: 'none'
                        });
                        return false;
                    }
                    if (o.success) o.success(res.data);
                } else {
                    wx.showToast({
                        title: '请求错误',
                        icon: 'none'
                    });
                }
            },
            fail: function (res) {
                if (show) {
                    wx.hideLoading();
                }
                wx.showToast({
                    title: '请求错误',
                    icon: 'none'
                });
            }
        })
    },
    //重写分享方法
    // overShare: function() {
    // 	//监听路由切换
    // 	//间接实现全局设置分享内容
    // 	wx.onAppRoute(function(res) {
    // 		//获取加载的页面
    // 		let pages = getCurrentPages(),
    // 			//获取当前页面的对象
    // 			view = pages[pages.length - 1],
    // 			data;
    // 		if (view) {
    // 			data = view.data;
    // 			console.log('是否重写分享方法', data.isOverShare);
    // 			if (!data.isOverShare) {
    // 				data.isOverShare = true;
    // 				view.onShareAppMessage = function() {
    // 					//你的分享配置
    // 					return {
    // 						title: '标题',
    // 						path: '/pages/index/index'
    // 					};
    // 				}
    // 			}
    // 		}
    // 	})
    // },
    //门锁接口封装
    doors: function (o, show) {
        if (show) {
            wx.showLoading({
                mask: true,
                title: '正在加载...'
            });
        }
        var data = o.data || {};
        var openLockToken = wx.getStorageSync('openLockAccessToken')
        wx.request({
            url: this.unlocking + o.url,
            data: data,
            method: o.method || 'POST',
            header: o.header || {},
            success: function (res) {
                if (show) {
                    wx.hideLoading();
                }
                if (o.success) o.success(res.data);

            },
            fail: function (res) {
                if (show) {
                    wx.hideLoading();
                }
                wx.showToast({
                    title: '请求错误',
                    icon: 'none'
                });
            }
        })
    }
})
